import { Breadcrumb, Button, Table, Space, TableProps, message } from 'antd';
import React, { FC } from 'react';
import { FormPanel, FormPanelBtnAlign, type FormPanelObject, InputType } from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import { YES_NO } from '@/constant/basicOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import Settings from './settings';
import Certification from './certification';
import { getPathRoot } from '@/utils';
import { StuGraduationSrv } from '@/service/student';
import { GRADUATION_STATUS } from '@/constant/studentOptions';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import { searchSchoolOptions } from '@/service/options';
import dayjs from 'dayjs';


const _dataSource = [
  {
    key: '1',
    student_name: '张三',
    status: 'graduation',
    isCompleted: true,
    class: '三(2)',
    school: '浑南区实验小学北校',
    timestamp: '2016-09-21',
    school_id: 1,
  },
  // 更多数据项...
];
const Groups: FC = () => {
  const [loading, setLoading] = React.useState(false);
  const [dataSource, setDataSource] = React.useState(_dataSource);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState<FormPanelObject>(null);
  const [showSettingsModel, setShowSettingsModel] = React.useState(false);
  const [showCertificationsModel, setShowCertificationModel] = React.useState(false);
  const [currentRow, setCurrentRow] = React.useState(null);

  //const country = useCountry();
  const [selectionType, setSelectionType] = React.useState<'checkbox' | 'radio'>('checkbox');

  const [selectedSchools, setSelectedSchools] = React.useState([]);

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelectedSchools(selectedRows.map(it => it.school_id));
    },
    getCheckboxProps: (record: any) => {
        return {
            disabled: record.archive_status, // Column configuration not to be checked
            name: record.school_id,
        }
      
    },
  };
  
  const navigate = useNavigate();

  React.useEffect(() => {
    //fetchData({ page: pageIndex, per_page: pageSize });
  }, []);

  const pageChange = (page, per_page) => {
    // setPageIndex(pageIndex);
    // setPageSize(pageSize);
    fetchData({ ...form?.getFieldsValue(), page, per_page });
  };

  /** 获取数据 */
  const fetchData = async params => {
    console.log('🚀 ~ fetchData ~ params:', params);

    setLoading(true);
    try {
      const { success, data } = await StuGraduationSrv.list(params);
      console.log('🚀 ~ fetchData ~ data:', data);
      if (success) {
        setDataSource(data.items);
        setTotal(data.total);
        setPageSize(params.per_page);
        setPageIndex(params.page);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  function handleView(route, record) {
    console.log('查看', record);
    // navigate(`/newstudent/edit${record.id}`);
    navigate(`${getPathRoot()}/graduation/${route}/${record.student_id}`, { state: record });
  }

  function handleSettings(record) {
    console.log('设定', record);
    setCurrentRow({ ...record });
    setShowSettingsModel(true);
  }

  function handleOutFlow(record) {
    console.log('制定', record);
    setCurrentRow({ ...record });
    setShowCertificationModel(true);
  }

  const columns: TableProps['columns'] = [
    {
      title: '学校',
      dataIndex: 'school',
      key: 'school',
    },
    {
      title: '归档',
      dataIndex: 'archive_status',
      key: 'archive_status',
      render: (text: any) => {
        return _.find(YES_NO, { value: text })?.label;
      },
    },
    {
      title: '毕业生数量',
      dataIndex: 'graduate_count',
      key: 'graduate_count',
    },
    {
      title: '操作',
      key: 'actions',
      //width: 280,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          <PermissionButton permission="view">
            <Button type="link" onClick={() => handleView('details', record)}>
              查看
            </Button>
          </PermissionButton>
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      inputs: [
        {
          label: '学校',
          name: 'school_id',
          key: 'school_id',
          inputType: InputType.search,
          renderOption: searchSchoolOptions,
        },
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
          textRange: [0, 28],
        },
        {
          label: '毕业年月',
          name: 'graduation_date',
          key: 'graduation_date',
          inputType: InputType.dateRange,
          formatSubmitValue: (value, form: FormPanelObject) => {
            if (value && value.length === 2) {
              form.pushFieldValue(`graduation_date_s`, dayjs(value[0]).format('YYYY-MM-DD'));
              form.pushFieldValue(`graduation_date_e`, dayjs(value[1]).format('YYYY-MM-DD'));
            }
            
          }
        },
        {
          label: '状态',
          name: 'status',
          key: 'status',
          inputType: InputType.select,
          renderOption: GRADUATION_STATUS,
        },
        {
          label: '归档',
          name: 'archive_status',
          key:  'archive_status',
          inputType: InputType.select,
          renderOption: YES_NO,

        }
      ],
    },
  ];

  const onSettingsChange = (isRequest = false) => {
    if (isRequest) {
      fetchData({ ...form?.getFieldsValue(), page: pageIndex, per_page: pageSize });
    }
    setShowSettingsModel(false);
  };
  const onCertificationChange = (isRequest = false) => {
    if (isRequest) {
      fetchData({ ...form?.getFieldsValue(), page: pageIndex, per_page: pageSize });
    }
    setShowCertificationModel(false);
  };

  return (
    <PageContainer header={<Breadcrumb items={[{ title: '毕业生信息管理' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        onLoad={(form: FormPanelObject) => {
          setForm(form);
        }}
        onFinish={(form: FormPanelObject) => {
          const params = form.getFieldsValue();
          console.log(params, '========================>>>>')
          fetchData({ ...params, page: 1, per_page: pageSize });
          return false;
        }}
        onReset={() => {
          fetchData({ page: 1, per_page: pageSize });
          form.resetFields();
        }}
        template={list}
      />
      <Space style={{ margin: '0 0 10px' }}>
        <Button type='primary' onClick={() => {
          if (selectedSchools.length === 0) {
            message.warning('请选择');
            return;
          }
          StuGraduationSrv.allplaceOnFile(selectedSchools);
        }}>归档</Button>
      </Space>
      <Table
        rowSelection={{
            type: selectionType,
            ...rowSelection,
        }}
        dataSource={dataSource}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Settings show={showSettingsModel} onChange={onSettingsChange} formValue={currentRow} />
      <Certification show={showCertificationsModel} onChange={onCertificationChange} formValue={currentRow} />
    </PageContainer>
  );
};

export default Groups;
